<?php
    @include_once("conn.php");
    @include_once("./common.php");

    $user = $_POST["user"];
    $gid = $_POST["gid"];
    $buyNum = $_POST["buyNum"];

    if(!($user&&$gid&&$buyNum)){
        argErr();
    }

    // 无脑新增  => 如果已经买过了会再次插入一条数据 => 不好   
    // 买之前 判断判断 当前用户 是否购买 该商品

    // 判断判断 当前用户 是否购买 该商品
    $search = "select * from `shoppingcar` where user='$user' and gid = '$gid'";
    $result = mysqli_query($conn,$search);
    $item = mysqli_fetch_assoc($result);

    if($item){  // 该用户  买过这件商品   => 更新数量 = (原本的数量 + 再次购买的数量)
        $sql = "update `shoppingcar` set buyNum=buyNum+$buyNum where user='$user' and gid = '$gid'";
    }else {  // 没买过 就新增
        $sql = "insert  into `shoppingcar`(user,gid,buyNum) values('$user','$gid',$buyNum)";
    }

    mysqli_query($conn,$sql);  
    
    //  mysqli_query()
    // 查询  =>  接收结果对象 => 解析
    // 增删改 => 获取受影响的行数

    $rows = mysqli_affected_rows($conn);
    // 新增
    // >0
    // ==-1
    
    $obj = array();
    if($rows>0){
        $obj["status"] = true;
        $obj["detail"] = "加入成功";
    }else{
        $obj["status"] = false;
        $obj["detail"] = "加入失败";
        $obj["sql"] = $sql;
    }
   

    echo json_encode($obj);


?>